/**
 * 
 */
package net.mikoo.seals.manage.web.interceptor;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import net.mikoo.seals.biz.service.CompanyService;
import net.mikoo.seals.biz.service.CustosService;
import net.mikoo.seals.biz.service.StaffServices;
import net.mikoo.seals.biz.service.UserLoginServices;
import net.mikoo.seals.common.WebContext;
import net.mikoo.seals.common.enums.CustosStatusEnum;
import net.mikoo.seals.common.enums.CustosTypeEnum;
import net.mikoo.seals.common.enums.MobileStatusEnum;
import net.mikoo.seals.common.enums.PartyTypeEnum;
import net.mikoo.seals.common.enums.StaffTypeEnum;
import net.mikoo.seals.model.Company;
import net.mikoo.seals.model.Custos;
import net.mikoo.seals.model.CustosQuery;
import net.mikoo.seals.model.Party;
import net.mikoo.seals.model.Person;
import net.mikoo.seals.model.Staff;
import net.mikoo.seals.model.StaffQuery;

/**
 * @author huangxm
 *
 */
public class MemberInterceptor implements HandlerInterceptor {

	Logger logger = Logger.getLogger(MemberInterceptor.class);
	
	@Autowired
	private UserLoginServices userLoginServices;
	
	@Autowired
	private CustosService custosService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private StaffServices staffServices;
	

	/**
	 * 
	 */
	public MemberInterceptor() {
	}
	
	
	
	public void  autoLogin(HttpServletRequest request){
		//String username = servletContext.getInitParameter("username");
		//String password = servletContext.getInitParameter("password");
		String username = "16621376939";
		String password = "111111";
		
		if(StringUtils.isNotEmpty(username.toString()) && StringUtils.isNotEmpty(password.toString())){
			HttpSession session = request.getSession();
			Object obj = session.getAttribute(WebContext.ADMIN_LOGIN_SESSION_KEY);
			
			if(obj == null){
				Party party = userLoginServices.authLogin(username,password,PartyTypeEnum.OPERATOR.getCode());
				if(party != null){
					session.setAttribute(WebContext.ADMIN_LOGIN_SESSION_KEY, party);
					
				}
			}
		}
		
	}
	
	

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		
		//autoLogin(request);
		initActionState(request);

		HttpSession session = request.getSession();
		Object obj = session.getAttribute(WebContext.ADMIN_LOGIN_SESSION_KEY);
		if(obj != null){
			
			Party party = (Party)obj;
			String mobileStatus = party.getPerson().getMobileStatus();
			if(mobileStatus.equals(MobileStatusEnum.NOT_CERTIFIED.code())) {
				response.sendRedirect("/check.htm");
				return false;
			}
			
			Object comObjct = session.getAttribute(WebContext.ADMIN_COMPANY_KEY);
			if(comObjct == null) {
				
				List<Company> companys = companyService.getListByPartyId(party.getPartyId());
				if(companys == null) {
					response.sendRedirect("/login.htm");
					return false;
				}
				
				if(companys.size() == 1) {
					Company company = companys.get(0);
					session.setAttribute(WebContext.ADMIN_COMPANY_KEY, company);
				}else {
					response.sendRedirect("/company.htm");
					return false;
				}
			}
			
			
			initInfo(request);
			initPerms(request);
			return true;
		}
		
		
		response.sendRedirect("/login.htm");
		
		return false;
	}
	
	
	
	private void initPerms(HttpServletRequest request) {

		HttpSession session = request.getSession();
		Object partyObj = session.getAttribute(WebContext.ADMIN_LOGIN_SESSION_KEY);
		Object comyObj = session.getAttribute(WebContext.ADMIN_COMPANY_KEY);
		Party party = (Party) partyObj;
		Company company = (Company) comyObj;

		
		StaffQuery staffQuery = new StaffQuery();
		staffQuery.setPartyId(party.getPartyId());
		staffQuery.setCompanyId(company.getCompanyId());
		Staff staff = staffServices.getInfoByQuery(staffQuery);
		
		// 判断是否是系统管理员
		if (staff.getStaffType().equals(StaffTypeEnum.ADMIN.code())) {
			request.setAttribute("_USER_ROLE", "ADMIN");
		}
		
		if (staff.getStaffType().equals(StaffTypeEnum.LEGAL_PERSON.code())) {
			request.setAttribute("_USER_ROLE", "LEGAL_PERSON");
		}

		// 判断是否是印章管理员
		CustosQuery query = new CustosQuery();
		query.setCompanyId(company.getCompanyId());
		query.setPartyId(party.getPartyId());
		query.setCustosType(CustosTypeEnum.CUSTOS.code());
		query.setCustosStatus(CustosStatusEnum.EFFECTIVE.code());
		List<Custos> custoses = custosService.getListByQuery(query);
		if (custoses != null && !custoses.isEmpty()) {
			
			Object userRole = request.getAttribute("_USER_ROLE");
			if(userRole != null) {
				if(userRole.toString().equals("LEGAL_PERSON")) {
					request.setAttribute("_USER_ROLE", "LEGAL_PERSON_CUSTOS");
				}else {
					request.setAttribute("_USER_ROLE", "ADMIN_CUSTOS");
				}
				
			}else {
				request.setAttribute("_USER_ROLE", "CUSTOS");
			}
		}

	}
	
	private void initInfo(HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		Object obj = session.getAttribute(WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		Object comObjct = session.getAttribute(WebContext.ADMIN_COMPANY_KEY);
		
		Party party = (Party)obj;
		Company company = (Company)comObjct;
		
		Person person = party.getPerson();
		if(StringUtils.isNotBlank(person.getName())) {
			
			request.setAttribute("_loginName", person.getName());
		}else {
			request.setAttribute("_loginName", party.getUserLoginId());
		}
		request.setAttribute("_portrait", person.getPortrait());
		request.setAttribute("_companyName", company.getCompanyName());
	}

	public void initActionState(HttpServletRequest request) {
		try {
			String path = request.getServletPath();
			Pattern p = Pattern.compile("\\/(.*?)\\/");// 正则表达式，取q#和#q之间的字符串，不包括q#和#q
			Matcher m = p.matcher(path);
			boolean b = m.find();
			if(b) {
				request.setAttribute("_actions", m.group(1));
			}else {
				request.setAttribute("_actions", "index");
			}
			
		}catch (Exception e) {
			logger.info("访问未匹配");
			request.setAttribute("_actions", "index");
		}
	}

	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// TODO Auto-generated method stub

	}

}
